import 'dart:ffi';

import 'package:cher_flare/routes/app_pages.dart';
import 'package:cher_flare/utils/ly_medal_manager.dart';
import 'package:cher_flare/utils/size_fit.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../utils/app_color.dart';
import 'ly_congratulations_page.dart';

class HomeContentPage extends StatefulWidget {
  const HomeContentPage({super.key});

  @override
  State<HomeContentPage> createState() => _HomeContentPageState();
}

class _HomeContentPageState extends State<HomeContentPage>
    with SingleTickerProviderStateMixin {
  late AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
        vsync: this,
        duration: const Duration(milliseconds: 500),
        reverseDuration: const Duration(milliseconds: 500),
        value: 0,
        lowerBound: -10,
        upperBound: 10);
    animationController.repeat(reverse: true);
    LYHomeDataManager.share.initMedal().then((value) {
      setState(() {});
    });
  }

  @override
  void dispose() {
    animationController.stop();
    animationController.dispose();
    super.dispose();
  }

  void _itemDidClick(int index) {
    if (LYHomeDataManager.share.willUnlockIndex == index) {
      Get.toNamed(AppPages.publishRecord)?.then((value) {
        if (value != null && value == true) {
          Get.dialog(
              LYCongratulationsPage(
                type: LYHomeDataManager.share
                    .initMedalType(LYHomeDataManager.share.currentUnlockTree),
              ),
              barrierDismissible: false,
              useSafeArea: false);
          setState(() {});
        }
      });
    }
  }

  void _itemMedalDidClick(int index) async {
    debugPrint('=============${LYHomeDataManager.share.currentUnlockTree}');
    final type = LYHomeDataManager.share.initMedalType(index);
    final isUnlock = await LYHomeDataManager.share.isMedalUnLock(type);
    if (index == LYHomeDataManager.share.currentUnlockTree && !isUnlock) {
      Get.toNamed(AppPages.medalPage)?.then((value) {
        setState(() {});
      });
    }
    // if (index == LYHomeDataManager.share.currentUnlockMedal.value + 1) {
    //   Get.toNamed(AppPages.medalPage)?.then((value) {
    //     setState(() {});
    //   });
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          image: DecorationImage(
        image: AssetImage('assets/images/home_bg.png'),
        fit: BoxFit.cover,
      )),
      child: SafeArea(
        bottom: false,
        child: Stack(
          children: [
            Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Image.asset(
                  'assets/images/home_tip_img.png',
                  width: LYSizeFit.screenWidth,
                )),
            Positioned(
              top: 3.px,
              right: 20.px,
              child: InkWell(
                onTap: () {
                  _strategyButtonDidClick();
                },
                child: Container(
                  alignment: Alignment.center,
                  width: 105.px,
                  height: 38.px,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/home_strategy_btn.png'),
                      fit: BoxFit.cover,
                    ),
                  ),
                  child: const Text(
                    'Strategy',
                    style: TextStyle(
                        fontSize: 14,
                        color: AppColors.color162b09,
                        fontWeight: FontWeight.w400),
                  ),
                ),
              ),
            ),
            Positioned(
                top: 200,
                left: 26,
                child: _makeAnimationItem(
                    child: _makeItem(
                      imgName: 'home_germination_img',
                      topImg: 'home_1_top.png',
                      title: 'Germination',
                      height: 100,
                      width: 108,
                      topLeft: 3,
                      topW: 87,
                      topH: 34,
                      isUnLock: LYHomeDataManager.share.willUnlockIndex >= 1,
                      onTap: () => _itemDidClick(0),
                      onTapMedal: () => _itemMedalDidClick(0),
                    ),
                    needAnimation:
                        LYHomeDataManager.share.willUnlockIndex == 0)),
            Positioned(
                top: 230,
                right: 2,
                child: _makeAnimationItem(
                    child: _makeItem(
                      imgName: 'home_seedling_stage_img',
                      topImg: 'home_2_top.png',
                      title: 'Seedling Stage',
                      height: 86,
                      width: 82,
                      topLeft: 11,
                      topW: 65,
                      topH: 41,
                      isUnLock: LYHomeDataManager.share.willUnlockIndex >= 2,
                      onTap: () => _itemDidClick(1),
                      onTapMedal: () => _itemMedalDidClick(1),
                    ),
                    needAnimation:
                        LYHomeDataManager.share.willUnlockIndex == 1)),
            Positioned(
                bottom: 90,
                right: 13,
                child: _makeAnimationItem(
                    child: _makeItem(
                      imgName: 'home_sapling_stage_img',
                      topImg: 'home_3_top.png',
                      title: 'Sapling Stage',
                      height: 82,
                      width: 83,
                      topLeft: 13,
                      topW: 72,
                      topH: 36,
                      isUnLock: LYHomeDataManager.share.willUnlockIndex >= 3,
                      onTap: () => _itemDidClick(2),
                      onTapMedal: () => _itemMedalDidClick(2),
                    ),
                    needAnimation:
                        LYHomeDataManager.share.willUnlockIndex == 2)),
            Positioned(
                bottom: 90,
                left: 8,
                child: _makeAnimationItem(
                    child: _makeItem(
                      imgName: 'home_mature_stage_img',
                      topImg: 'home_4_top.png',
                      title: 'Mature Stage',
                      height: 100,
                      width: 108,
                      topLeft: 2,
                      topW: 71,
                      topH: 39,
                      isUnLock: LYHomeDataManager.share.willUnlockIndex >= 4,
                      onTap: () => _itemDidClick(3),
                      onTapMedal: () => _itemMedalDidClick(3),
                    ),
                    needAnimation:
                        LYHomeDataManager.share.willUnlockIndex == 3)),
          ],
        ),
      ),
    );
  }

  Widget _makeAnimationItem({
    required Widget child,
    required bool needAnimation,
  }) {
    if (!needAnimation) {
      return child;
    }
    return AnimatedBuilder(
      animation: animationController,
      child: child,
      builder: (BuildContext context, Widget? child) {
        return Transform.translate(
          offset: Offset(0, animationController.value),
          child: child,
        );
      },
    );
  }

  Widget _makeItem({
    required String imgName,
    required String topImg,
    required String title,
    required double height,
    required double width,
    required double topLeft,
    required double topW,
    required double topH,
    required Function() onTap,
    required Function() onTapMedal,
    bool isUnLock = false,
  }) {
    return SizedBox(
      width: 108,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisSize: MainAxisSize.min,
        children: [
          InkWell(
              onTap: onTapMedal,
              child: Padding(
                  padding: EdgeInsets.only(left: topLeft),
                  child: Image.asset('assets/images/$topImg',
                      width: topW, height: topH))),
          InkWell(
            onTap: onTap,
            child: Image.asset(
              'assets/images/${imgName}_${isUnLock ? "unlock" : "lock"}.png',
              width: width,
              height: height,
            ),
          ),
          Container(
            padding: const EdgeInsets.only(top: 4),
            alignment: Alignment.center,
            child: Text(
              title,
              style:
                  const TextStyle(color: AppColors.color404040, fontSize: 12),
            ),
          ),
        ],
      ),
    );
  }

  void _strategyButtonDidClick() {
    Get.toNamed(AppPages.strategyPage);
  }
}
